<?php

class userController extends Controller
{
	public function show()
	{
		$this->assign('groups',	Group::instance()->getList());
		$this->assign('list',	User::instance()->getList());
		$this->display();
	}

	/**
	 * 开关用户状态
	 */
	public function disa()
	{
		$uid	=	fetch_get('user_id', 'int');
		$disa	=	fetch_get('disa', 'int');
		if(!$uid) {
			Show::warning("参数错误");
		}

		$disa	=	$disa?0:1;
		if(!User::instance()->update($uid, array('is_disa'=>$disa))) {
			Show::warning("修改失败!");
		}

		Show::ajaxBand(array(
			'user_id'	=>	$uid,
			'disa'		=>	$disa,
		));
		Show::notice("修改用户状态成功");
	}
	
	/**
	 * 增加和修改
	 */
	public function save()
	{
		$user_id	=	fetch_post('user_id', 'int');

		if(!$user_id && !fetch_post('name')) {
			Show::warning("请输入正确的用户名");
		}
		if(!fetch_post('group_id', 'int')) {
			Show::warning("请选择正确的用户组");
		}

		if(!$user_id)
		{
			$user_id	=	UserHelper::add(fetch_post('name'), fetch_post('passwd','char'), fetch_post('nickname'), fetch_post('email'));
			UserHelper::joinGroup($user_id, fetch_post('group_id','int'));
			Show::ajaxBand(array('method'=>'insert'));
		}
		else
		{
			UserHelper::modify($user_id, fetch_post('passwd','char'), fetch_post('nickname'), fetch_post('email'));
			UserHelper::joinGroup($user_id, fetch_post('group_id','int'));
			Show::ajaxBand(array('method'=>'update'));
		}

		$this->assign('groups',	Group::instance()->getList());
		$this->assign('u', User::instance()->get($user_id));
		$html	=	$this->fetch('user-saved');

		Show::ajaxBand(array(
			'html'		=>	$html,
			'user_id'	=>	$user_id,
		));
		Show::notice("保存成功！");
	}

	/**
	 * 角色管理
	 */
	public function role()
	{
		$id	=	fetch_get('id', 'int');
		if(!$id) {
			Show::error("参数错误", 'user');
		}

		$user	=	User::instance()->get($id);
		if(!$user) {
			Show::error("无此用户", 'user');
		}

		//处理post授权
		if(fetch_post('user_id','int'))
		{
			$user_id	=	fetch_post('user_id', 'int');
			UserHelper::purgeRoles($user_id);
			if(!empty($_POST['role'])) {
				UserHelper::assumeRole($user_id, $_POST['role']);
			}
			Show::notice("授与成功");
		}

		$roles	=	UserHelper::getRoles($id);
		$rids	=	array();
		foreach($roles as $r) {
			$rids[]	=	$r['role_id'];
		}

		$user['roles']	=	$roles;
		$user['group_title']	=	Group::instance()->getTitle($user['group_id']);
		
		$this->assign('user',	$user);
		$this->assign('user_roles',	$rids);
		$this->assign('roles',	Role::instance()->getRealList());
		
		$this->display();
	}

	/**
	 * 删除
	 */
	public function delete()
	{
		if(!fetch_get('user_id', 'int')) {
			Show::error("参数错误");
		}
		if(RoleHelper::delete(fetch_get('user_id', 'int'))) {
			Show::notice("删除成功");
		}
		else {
			Show::warning("删除失败");
		}
	}
	
}

?>
